<template>
	<view class="container">
		<scroll-view scroll-y class="scroll-container">

			<!-- 日历组件 -->
			<uni-calendar :lunar="false" @change="handleDateChange" :date="currentDate" :selected="selectedDates"
				@monthSwitch="handleMonthSwitch" :showMonth="false"></uni-calendar>

			<!-- 上午下午切换 -->
			<view class="time-tabs">
				<view v-for="(time, idx) in timeTabs" :key="idx"
					:class="['time-tab', activeTimeTab === idx ? 'active' : '']" @click="switchTimeTab(idx)">
					{{ time }}
				</view>
			</view>

			<!-- 值班信息展示 -->
			<view v-if="selectedDutyDate" class="duty-info">
				<view class="date-title">{{ selectedDutyDate }}</view>

				<view class="section">
					<view class="section-title"> 带班领导：</view>
					<view v-if="selectedLeaders.length > 0" class="staff-list">
						<text v-for="leader in selectedLeaders" :key="leader.id"
							:class="['staff-item', { highlighted: leader.name === currentUserName }]">
							{{ leader.name }}
						</text>
					</view>
					<view v-else class="no-data">暂无带班领导</view>
				</view>

				<view class="section">
					<view class="section-title"> 值班人员：</view>
					<view v-if="selectedStaffs.length > 0" class="staff-list-staff">
						<text v-for="staff in selectedStaffs" :key="staff.id"
							:class="['staff-item', { highlighted: staff.name === currentUserName }]">
							{{ staff.name }}
						</text>
					</view>
					<view v-else class="no-data">暂无值班人员</view>
				</view>
			</view>

			<view v-else class="no-selection">
				请选择一个有值班安排的日期查看详细信息。
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentUserName: uni.getStorageSync('userInfo')?.username || '', // 当前用户姓名
				loading: false,
				currentDate: '', // 当前选择的日期
				selectedDutyDate: null, // 实际选中的有值班的日期
				scheduleData: {}, // 值班数据
				selectedDates: [], // 日历中标注的有值班日期
				timeTabs: ['上午', '下午'],
				activeTimeTab: 0
			};
		},
		computed: {
			selectedLeaders() {
				if (!this.selectedDutyDate) return [];
				const timeKey = this.activeTimeTab === 0 ? 'morning' : 'afternoon';
				return this.scheduleData[this.selectedDutyDate]?.leaders?.[timeKey] || [];
			},
			selectedStaffs() {
				if (!this.selectedDutyDate) return [];
				const timeKey = this.activeTimeTab === 0 ? 'morning' : 'afternoon';
				return this.scheduleData[this.selectedDutyDate]?.staffs?.[timeKey] || [];
			}
		},
		created() {
			this.initData();
		},
		methods: {
			initData() {
				const today = this.getDateString(new Date());
				this.currentDate = today;
				this.loadDutyData(today).then(() => {
					// 默认选中当天，不管当天是否有排班
					this.handleDateChange({
						fulldate: today
					});
				});
			},
			async loadDutyData(selectedDate) {
				const [year, month] = selectedDate.split('-');
				const startDate = `${year}-${month}-01`;
				const endDate = `${year}-${month}-${new Date(year, month, 0).getDate()}`;

				this.loading = true;
				try {
					const obj = uniCloud.importObject('duty');
					const res = await obj.getDuty({
						startDate,
						endDate
					});

					if (res.code === 0) {
						this.scheduleData = {}; // 重置数据

						res.data.forEach(item => {
							const date = item.date.split('T')[0]; // 去除时间部分
							this.scheduleData[date] = {
								leaders: {
									morning: item.leaders?.morning || [],
									afternoon: item.leaders?.afternoon || []
								},
								staffs: {
									morning: item.staffs?.morning || [],
									afternoon: item.staffs?.afternoon || []
								}
							};
						});

						this.selectedDates = Object.keys(this.scheduleData).map(date => ({
							date,
							info: '值班'
						}));

					} else {
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					}

				} catch (e) {
					//console.error('加载错误:', e);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			handleMonthSwitch(e) {
				// //console.log(e,'handleMonthSwitch')
				const year = e.year;
				const month = String(e.month).padStart(2, '0'); // 补零，如 4 → '04'
				const day = '01'; // 固定第一天
				const selectedDateStr = `${year}-${month}-${day}`;
				//console.log(selectedDateStr,'handleMonthSwitch')
				this.loadDutyData(selectedDateStr)
			},
			handleDateChange(e) {
				//console.log(e,'handleDateChange')
				const selectedDate = this.getDateString(new Date(e.fulldate));
				this.currentDate = selectedDate;

				// 判断该日期是否有值班数据
				if (this.scheduleData[selectedDate]) {
					this.selectedDutyDate = selectedDate;
				} else {
					this.selectedDutyDate = null;
				}
			},
			switchTimeTab(index) {
				this.activeTimeTab = index;
			},
			getDateString(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		height: 100%;
		// padding: 20rpx;
		// background-color: #f9f9f9;
		// min-height: 100vh;
	}

	.scroll-container {
		height: 100%;
		overflow: hidden;
	}

	.time-tabs {
		display: flex;
		margin-top: 20rpx;
		border-bottom: 2rpx solid #eee;
		background-color: #fff;
		z-index: 10;
	}

	.time-tab {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			color: #007AFF;
			font-weight: 500;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 4rpx;
				background-color: #007AFF;
			}
		}
	}

	.duty-info {
		margin-top: 40rpx;
		background-color: #fff;
		padding: 30rpx;
		border-radius: 20rpx;
		box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.date-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
		text-align: center;
		color: #333;
	}

	.section {
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.staff-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		max-height: 300rpx; // 控制最大高度
		overflow-y: auto; // 允许内部滚动
		padding: 10rpx 0;
	}

	.staff-list-staff {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		max-height: 300rpx; // 控制最大高度
		overflow-y: auto; // 允许内部滚动
		padding: 10rpx 0;
		margin-bottom: 300rpx;
	}

	/* 可选：美化滚动条（仅在支持的平台生效） */
	.staff-list::-webkit-scrollbar {
		width: 6rpx;
	}

	.staff-list::-webkit-scrollbar-thumb {
		background-color: rgba(0, 122, 255, 0.3);
		border-radius: 3rpx;
	}

	.staff-item {
		background-color: #f0f8ff;
		padding: 6rpx 20rpx;
		border-radius: 40rpx;
		margin-right: 20rpx;
		margin-bottom: 10rpx;
		font-size: 28rpx;
		color: #333;

		&.highlighted {
			background-color: #ffd700; // 或你喜欢的颜色
			color: #000;
			font-weight: bold;
		}
	}

	.no-data {
		color: #999;
		font-size: 26rpx;
	}

	.no-selection {
		margin-top: 100rpx;
		text-align: center;
		color: #888;
		font-size: 28rpx;
	}
</style>